<?php
require_once("../../../config.inc.php");
$isReloadable = false;
require_once("../../../app/_inc/include.php");
require_once("../_inc/procFunction.php");

$errMsg = "";
$module = sxREQ('mod');
$name = sxREQ('name');

if($module == ""){	
	$url = $_SESSION[USEROBJ]->getHistory(0, true).
		"&msg=".urlencode(_t("missing cod. 'mod'"));
	serverRedir($url);
}
if($name == ""){	
	$url = $_SESSION[USEROBJ]->getHistory(0, true).
		"&msg=".urlencode(_t("missing cod. 'name'"));
	serverRedir($url);
}

$aVarAbil = getCrulVarAbil($module, $name);
$sFieldList = implode(", ",array_keys($aVarAbil));

if(sxREQ("reqtype") == "save"){
	$errMsg .= updateScript($aVarAbil);
}
$sSQL = "SELECT * FROM com_rule 
			WHERE module='$module' 
			AND name='$name'";
$objSDAO->query($sSQL,"selep");
$row = $objSDAO->fetch("selep");
if(!$row){	
	$url = $_SESSION[USEROBJ]->getHistory(0, true).
		"&msg=".urlencode(_t("missing  name $module/$name"));
	serverRedir($url);
}
sxRDef('name', $row['name']);
sxRDef('description', $row['description']);
sxRDef('script', $row['script']);


$aOpz = array("kMenu"=>'pro.cru', "isReloadable"=>$isReloadable);
echo(headerHTML($aOpz));
?>
<script language="JavaScript" type="text/javascript">
function objFrmSubm(rt){
	document.objFrm.reqtype.value = rt;
	document.objFrm.submit();
}
</script>
  
<?php
echo(bodyHTML($aOpz));

echo getModHeader($module);

$aCmd = array("save"=>array("pag"=>"javascript:objFrmSubm('save')",
										"title"=>_t("save"),
										"text"=>_t("save")
										),
					"back"=>array()
					);
$sCmd = commandsHTML($aCmd);	
echo $sCmd;

echo getHtmlForm('objFrm');
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('reqtype','...');
echo getHtmlHidden('mod');
echo getHtmlHidden('name');

echo("<table class=\"tabl01\" width=\"100%\" cellpadding=\"3\" cellspacing=\"2\" border='0'>\n");
echo("<tr>" .
			"<td class=\"titl01\" width=\"20%\" colspan='5'>Common Rule Script</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\" width=\"20%\">Name</td>" .
			"<td class=\"text01\" width=\"10%\">".getHtmlVisText('name')."</td>" .
			"<td class=\"labl01\" width=\"15%\">Description</td>" .
			"<td class=\"text01\" width=\"55%\" colspan='2'>".getHtmlVisText('description')."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Script<br>" .
			"<input type='checkbox' name='reformat' id='reformat' class='labl01'> re-format ");
echo("<td class=\"text01\" colspan='3'>" 
			.getHtmlTextAreaScript('script',75,20)
			."</td>\n");
echo("<td class=\"text01\">" 
			.$sFieldList
			."</td></tr>\n");
echo("</table>");

echo(commandsHTML($aCmd));
echo("</form>");
echo("</td>\n</tr>\n</table>\n");

echo(footerHTML());
exit();

function updateScript($aVarAbil){
	global $objSDAO;
	$errMsg = "";
	if(sxRTrim("mod") == '')
		$errMsg .= "missing module<br>";
	if(sxRTrim("name") == '')
		$errMsg .= "missing name old<br>";
		
	//check script
	$script = sxRTrim("script");
	$objParse = new polarisParser;
	if(!$objParse->parse($script)) {
		return $objParse->getError();
	}
	//dbg_("aVarAbil: ".print_r($aVarAbil,1));
	//dbg_("objParse->aVariables: ".print_r($objParse->aVariables,1));
	foreach($objParse->aVariables as $varName => $aPropVar) {
		if (strpos('TRS_',$varName[0])!== false) { // temporary or system variable
			continue;
		}
		if (!isset($aVarAbil[$varName])) {
			$errMsg .= _t("variable '%s' not available",$varName)."<br>";
			continue;
		}
		if ($aPropVar['modified'] and $aVarAbil[$varName] == 'Y') {
			$errMsg .= _t("variable '%s' read-only",$varName)."<br>";
		}
	}

	$aFunzDisp = getCrulFunzDisp();
	foreach($objParse->aFunctions as $funzName => $aFunzVar) {
		if (!isset($aFunzDisp[$funzName])) {
			$errMsg .= _t("function '%s' not available",$funzName)."<br>";
			continue;
		}
		if ($aFunzVar['numPar'] !=  count($aFunzDisp[$funzName])) {
			$errMsg .= _t("function '%s' with %s parameters - required %s",
				$funzName,$aFunzVar['numPar'],count($aFunzDisp[$funzName]))."<br>";
		}
	}
		
	if($errMsg != "") {
		return $errMsg;
	}	
	if (sxREQ('reformat')=='Y') {
		$script = $objParse->getFormatCode();
	}
	
	$aModComR = explode('.',sxREQ('com_rule'));
	$sSQL = "UPDATE com_rule SET script = '".sxAS($script)."'" .
			" WHERE name='".sxRAS("name")."'" .
			" AND module='".sxRAS("mod")."'";
	$objSDAO->exec($sSQL);
	$url = $_SESSION[USEROBJ]->getHistory(0, true);
	serverRedir($url);
	return 'redir err';
}

function getCrulVarAbil($module, $name) {
	global $objSDAO;
	$aVarAbil = array(); 
	$sSQL = "SELECT cra.com_alias, a.attribute, cra.read_only " .
			" FROM com_rule_alias cra " .
			" INNER JOIN attribute a ON a.entity = cra.entity " .
			" WHERE cra.module='$module' " .
			"    AND cra.name='$name'";	
	$objSDAO->query($sSQL,"x");
	while($row = $objSDAO->fetch('x')) {
		$aVarAbil[$row['com_alias'].'_'.$row['attribute']] = $row['read_only'];
	}
	$sSQL = "SELECT cra.com_alias, crv.variable " .
			" FROM com_rule_alias cra " .
			" INNER JOIN com_rule_variable crv ON crv.module = cra.module AND crv.com_alias = cra.com_alias  " .
			" WHERE cra.module='$module' " .
			"    AND cra.name='$name'";	
	$objSDAO->query($sSQL,"x");
	while($row = $objSDAO->fetch('x')) {
		$aVarAbil[$row['com_alias'].'_'.$row['variable']] = 'N';
	}
	return $aVarAbil;
}

function getCrulFunzDisp() {
	global $objSDAO;
	$aFunzDisp = array(); 
	$sSQL = "SELECT f.result_type, f.function, f.library ,fv.variable_type " .
			" FROM `function` f " .
			" LEFT JOIN function_variable fv ON fv.function = f.function  " .
			" ORDER BY f.function, fv.sequence";	
	$objSDAO->query($sSQL,"x");
	while($row = $objSDAO->fetch('x')) {
		if (!isset($aFunzDisp[$row['function']])) {
			$aFunzDisp[$row['function']] = array();
		}
		if (!empty($row['variable_type'])) {
			$aFunzDisp[$row['function']][]=$row['variable_type'];
		}
	}
	return $aFunzDisp;
}
